/**
 * 用户相关服务
 */
const util = require('../utils/util.js')
const api = require('../config/api.js')

const LOGIN_USER = 'userInfo'
const TOKEN = 'token'
const ENTERPRISE_ID = 'enterpriseId'
const ENTERPRISE_NAME = 'enterpriseName'
const PLACE_ID = 'placeId'
const PLACE_NAME = 'placeName'

/**
 * Promise封装wx.login
 */
function wxLogin() {
  return new Promise(function(resolve, reject) {
    wx.login({
      success: function(res) {
        if (res.code) {
          resolve(res)
        } else {
          reject(res)
        }
      },
      fail: function(err) {
        reject(err)
      }
    })
  })
}

/**
 * 判断用户是否登录
 */
function checkLogin(callback) {

  return new Promise(function(resolve, reject) {
    let userInfo = getStorageUserInfo()
    resolve(userInfo)
  })
}

// 获取缓存中的用户信息
function getStorageUserInfo() {
  let userInfo = wx.getStorageSync(LOGIN_USER)
  return userInfo
}

function updateStorageUserInfo(userInfo) {
  if(userInfo){
    wx.setStorageSync(LOGIN_USER, userInfo)
    wx.setStorageSync(TOKEN, userInfo.token)

    wx.setStorageSync(ENTERPRISE_ID, userInfo.enterpriseId)
    wx.setStorageSync(ENTERPRISE_NAME, userInfo.enterpriseName)
    wx.setStorageSync(PLACE_ID, userInfo.placeId)
    wx.setStorageSync(PLACE_NAME, userInfo.placeName)
  }else{
    wx.removeStorageSync(LOGIN_USER)
    wx.removeStorageSync(TOKEN)

    wx.removeStorageSync(ENTERPRISE_ID)
    wx.removeStorageSync(ENTERPRISE_NAME)
    wx.removeStorageSync(PLACE_ID)
    wx.removeStorageSync(PLACE_NAME)
    
    wx.removeStorageSync('choosed_date')
  }
}

module.exports = {
  wxLogin: wxLogin, 
  checkLogin,
  getStorageUserInfo,
  updateStorageUserInfo
}